<template>
    <a-modal
        title="设备属性"
        :visible="visible"
        width="600px"
        ok-text="OK"
        cancel-text="Cancel"
        @ok="handleOk"
        @cancel="handleCancel"
    >
        <a-form-model ref="deviceForm" :model="form" :rules="rules" label-align="left" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-form-model-item label="设备名称" prop="name" required>
                <div style="display: flex; align-items: center;">
                    <a-input v-model="form.name" style="width: 100%; margin-right: 8px;" />
                    <a-button v-if="isOpcEnabled" type="primary" size="small" @click="handleOpcPreview">
                        Opc预览
                    </a-button>
                </div>
            </a-form-model-item>
            <a-form-model-item label="设备描述" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-textarea v-model="form.description" />
            </a-form-model-item>
            <a-form-model-item v-if="isOpcEnabled" label="OPC路径" prop="opc_path">
                <a-input v-model="form.extra.opc_path" style="width: 100%;" />
            </a-form-model-item>

            <a-tabs v-model="form.activeTab" class="protocol-tabs">
                <a-tab-pane key="general" tab="一般协议">
                    <a-form-model-item label="设备地址" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <a-input v-model="form.extra.address" style="width: 50%;" />
                        <a-checkbox v-model="form.extra.isHex" style="margin-left: 8px;" @change="handleHexChange">十六进制</a-checkbox>
                    </a-form-model-item>
                    <a-form-model-item label="浮点型(float)字节序" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <a-select v-model="form.extra.floatByteOrder">
                            <a-select-option value="ABCD">ABCD</a-select-option>
                            <a-select-option value="DCBA">DCBA</a-select-option>
                            <a-select-option value="BADC">BADC</a-select-option>
                            <a-select-option value="CDAB">CDAB</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="32位整型(int32/uint32)字节序" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <a-select v-model="form.extra.int32ByteOrder">
                            <a-select-option value="ABCD">ABCD</a-select-option>
                            <a-select-option value="DCBA">DCBA</a-select-option>
                            <a-select-option value="BADC">BADC</a-select-option>
                            <a-select-option value="CDAB">CDAB</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="64位整型(int64/uint64)字节序" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <a-select v-model="form.extra.int64ByteOrder">
                            <a-select-option value="ABCDEFGH">ABCDEFGH</a-select-option>
                            <a-select-option value="GHEFCDAB">GHEFCDAB</a-select-option>
                            <a-select-option value="BADCFEHG">BADCFEHG</a-select-option>
                            <a-select-option value="HGFEDCBA">HGFEDCBA</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="双精度浮点型(double)字节序" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <a-select v-model="form.extra.doubleByteOrder">
                            <a-select-option value="ABCDEFGH">ABCDEFGH</a-select-option>
                            <a-select-option value="GHEFCDAB">GHEFCDAB</a-select-option>
                            <a-select-option value="BADCFEHG">BADCFEHG</a-select-option>
                            <a-select-option value="HGFEDCBA">HGFEDCBA</a-select-option>
                        </a-select>
                    </a-form-model-item>
                </a-tab-pane>
                <a-tab-pane key="lt645" tab="LT645-2007电表协议" force-render :disabled="!isLt645TabEnabled">
                    <a-form-model-item label="协议地址" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <div style="display: flex; align-items: center;">
                            <a-input v-model="form.extra.protocolAddress" />
                            <span class="input-suffix">Enter补齐</span>
                        </div>
                    </a-form-model-item>
                    <a-form-model-item label="协议设备密码" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
                        <div style="display: flex; align-items: center;">
                            <a-input v-model="form.extra.devicePassword" />
                            <span class="input-suffix">Enter补齐</span>
                        </div>
                    </a-form-model-item>
                </a-tab-pane>
            </a-tabs>
        </a-form-model>
    </a-modal>
</template>

<script>
import _ from 'lodash'

export default {
    name: 'DevicePropertiesModal',
    props: {
        visible: { type: Boolean, required: true },
        deviceData: { type: Object, default: () => ({}) },
        portProtoType: { type: String, default: '' }
    },
    data() {
        const initialFormState = {
            id: -1,
            monitor_port_id: -1,
            name: 'DeviceName',
            description: '',
            activeTab: 'general',
            extra: {
                address: '',
                isHex: false,
                floatByteOrder: 'ABCD',
                int32ByteOrder: 'ABCD',
                int64ByteOrder: 'ABCDEFGH',
                doubleByteOrder: 'ABCDEFGH',
                protocolAddress: '',
                devicePassword: '',
                opc_path: ''
            }
        }

        return {
            form: _.cloneDeep(initialFormState),
            rules: {
                name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }]
            },
            initialFormState
        }
    },
    computed: {
        // 判断LT645 tab是否可用
        isLt645TabEnabled() {
            return this.portProtoType === '3006'
        },
        // 判断是否显示OPC相关元素
        isOpcEnabled() {
            return this.portProtoType === '3112'
        }
    },
    watch: {
        deviceData: {
            handler(newData) {
                console.log('🔍 [DevicePropertiesModal] 设备数据更新:', newData)
                // 使用深度合并：以模板为基础，用后端数据覆盖对应字段
                if (newData && Object.keys(newData).length) {
                    // 1. 克隆完整的模板结构（确保所有字段都有默认值）
                    const template = _.cloneDeep(this.initialFormState)
                    // 2. 深度合并后端数据（只覆盖后端返回的字段，其他保持默认值）
                    this.form = _.merge(template, _.cloneDeep(newData))
                    console.log('✅ [DevicePropertiesModal] 数据合并完成:', {
                        模板字段: Object.keys(template.extra),
                        后端数据: newData,
                        合并结果: this.form
                    })
                } else {
                    this.form = _.cloneDeep(this.initialFormState)
                }
            },
            immediate: true,
            deep: false
        },
        visible: {
            handler(newVisible) {
                if (newVisible) {
                    console.log('🔍 [DevicePropertiesModal] 弹窗打开')
                }
            },
            immediate: false
        },
        portProtoType: {
            handler(newProtoType) {
                console.log('🔄 [DevicePropertiesModal] 端口协议类型变化:', newProtoType)
            },
            immediate: true
        }
    },
    methods: {
        handleOk() {
            this.$refs.deviceForm.validate(valid => {
                if (valid) {
                    console.log('💾 [DevicePropertiesModal] 提交设备数据:', this.form)
                    this.$emit('ok', this.form)
                }
            })
        },
        handleCancel() {
            console.log('❌ [DevicePropertiesModal] 取消设备编辑')
            this.$emit('cancel')
        },
        handleOpcPreview() {
            console.log('🔍 [DevicePropertiesModal] OPC预览按钮点击，当前OPC路径:', this.form.extra.opc_path)
            // 实际应用中，这里可以打开一个新的窗口或弹窗来展示OPC数据
            // 例如：this.$emit('opcPreview', this.form.extra.opc_path)
            this.$message.info('OPC预览功能待实现')
        },
        handleHexChange() {
            const address = this.form.extra.address
            if (!address) {
                console.log('⚠️ [DevicePropertiesModal] 地址为空，跳过转换')
                return
            }

            try {
                if (this.form.extra.isHex) {    
                    // 十进制转十六进制
                    const decimal = parseInt(address, 10)
                    if (isNaN(decimal)) {
                        throw new Error('无效的十进制数值')
                    }
                    this.form.extra.address = '0x' + decimal.toString(16).toUpperCase()
                } else {
                    // 十六进制转十进制
                    const decimal = parseInt(address, 16)
                    if (isNaN(decimal)) {
                        throw new Error('无效的十六进制数值')
                    }
                    this.form.extra.address = decimal.toString(10)
                }
                console.log('✅ [DevicePropertiesModal] 地址转换成功:', this.form.extra.address)
            } catch (error) {
                console.error('❌ [DevicePropertiesModal] 地址转换失败:', error)
                this.$message.error('地址转换失败，请检查格式')
                // 发生错误时保持原值不变
                this.form.extra.address = address
            }
        }         
    }
}
</script>

<style scoped>
.protocol-tabs {
    border: 1px solid #d9d9d9;
    padding: 16px;
    border-radius: 4px;
    margin-top: 16px;
}
.ant-form-item {
    margin-bottom: 12px;
}
.input-suffix {
    margin-left: 8px;
    color: #999;
    width: 30%;
}
.ant-form-item-control-wrapper {
    display: flex;
    align-items: center;
}
</style> 